package cn.chousensei.chousenseiblog.controller;

import cn.chousensei.chousenseiblog.enums.LoginErrorEnum;
import cn.chousensei.chousenseiblog.model.User;
import cn.chousensei.chousenseiblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(@RequestParam String account,
                          @RequestParam String password,
                          HttpServletResponse response,
                          Model model) {
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        if (!userService.isSame(account)) {
            model.addAttribute("error", LoginErrorEnum.USER_NOT_EXIST.getMessage());
            return "login";
        }
        User userLogged = userService.isLoginSuccess(user);
        if (userLogged == null) {
            model.addAttribute("error", LoginErrorEnum.PASSWORD_ERROR.getMessage());
            return "login";
        } else {
            String token = UUID.randomUUID().toString();
            userLogged.setToken(token);
            userService.createOrUpdate(userLogged);
            response.addCookie(new Cookie("token", token));
        }
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
